﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using PS.Engine.GameComponents;

namespace PS.Engine.DataTypes
{
    public class PedestrianRandomStartZone : PedestrianZone
    {
        #region Private Members

        private bool isSetup = false;

        #endregion Private Members

        #region Constructors

        public PedestrianRandomStartZone()
            : base()
        {
        }

        public PedestrianRandomStartZone(int x, int y, int width, int height)
            : base(x, y, width, height)
        {
        }

        #endregion Constructors

        #region Public Properties

        public int Count { get; set; }
        public Vector2 Target { get; set; }

        #endregion Public Properties

        #region Public Overrides

        public override List<PedestrianSerializable> GetPedestrians()
        {
            if (!isSetup)
            {
                Setup();
            }

            return pedestrians;
        }

        #endregion Public Overrides

        #region Private Methods

        private void Setup()
        {
            // remove all pedestrians from zone
            pedestrians.Clear();

            // init random values
            Random randomX = new Random(ZoneRectangle.Right);
            int x;
            Random randomY = new Random(ZoneRectangle.Bottom);
            int y;

            // add all pedestrians to the zone at a random location
            for (int i = 0; i < Count; i++)
            {
                // get a unique random location
                do
                {
                    x = randomX.Next(ZoneRectangle.Left, ZoneRectangle.Right);
                    y = randomY.Next(ZoneRectangle.Top, ZoneRectangle.Bottom);
                }
                while (PedestrianExists(x, y));

                // add the pedestrian to the zone
                pedestrians.Add(new PedestrianSerializable(x, y, Target.X, Target.Y));
            }

            // set is setup flag (pedestrians are generated only once)
            isSetup = true;
        }

        // TODO: Der Mindestabstand zum nächstgelegenen Fussgänger sollte eingehalten werden (allenfalls unter Berücksichtigung des Verhaltens?)
        private bool PedestrianExists(int x, int y)
        {
            // check if there already is a pedestrian at the current location
            foreach (PedestrianSerializable pedestrian in pedestrians)
            {
                if (pedestrian.Location.X == x && pedestrian.Location.Y == y)
                {
                    // a pedestrian exists at current location
                    return true;
                }
            }

            // this location is unique :)
            return false;
        }

        #endregion Private Methods
    }
}
